//
//  DomainRenewalViewController.m
//  YinHang
//
//  Created by 张亚哲 on 14/10/28.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "DomainRenewalViewController.h"
#import "GetDomainInfo.h"

@interface DomainRenewalViewController ()<getDomainInfoDelegate,UITableViewDataSource,UITableViewDelegate,ASIHTTPRequestDelegate>{
    
    __weak IBOutlet UIButton *submitBtn;
    __weak IBOutlet UITableView *_tableView;
    GetDomainInfo *domainInfoService;
    
    __weak IBOutlet UITextField *domainNameTextField;
    
    __weak IBOutlet UITextField *pastTime;
    
    __weak IBOutlet UITextField *moneyTextField;
    
    NSArray *moneyList;
    
    MBProgressHUD *postHud;
    
    NSMutableArray *arr1;//单选控制
    
    NSInteger selectRow;//选中年限
    
    ASIFormDataRequest *submitInfo;//提交信息请求
    //参数
    NSDictionary *paramsDict;
    NSString *action;
}

@end

@implementation DomainRenewalViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewDidLayoutSubviews{
    CGRect frame = submitBtn.frame;
    if (IPHONE5) {
        submitBtn.frame = CGRectMake(frame.origin.x, frame.origin.y + 30, frame.size.width, frame.size.height);
    }
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    domainInfoService = [[GetDomainInfo alloc]initWithDomainId:_Id];
    domainInfoService.delegate = self;
    [domainInfoService getInfo];
    postHud = postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    postHud.labelText = @"正在加载，请稍后...";
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //标题
    self.navigationItem.title = @"域名管理";
    
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
    [self setUI];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma tableView Delegate Method
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"MoneyListCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"DomainCell" owner:nil options:nil][0];
    }
    NSInteger row = indexPath.row;
    UIImageView *img = (UIImageView *)[cell.contentView viewWithTag:1];
    
    UILabel *lbl = (UILabel *)[cell.contentView viewWithTag:2];
    lbl.text = [NSString stringWithFormat:@"%@年%@元",moneyList[row][@"year"],moneyList[row][@"money"]];
    if ([self contenthsHas:arr1 index:indexPath.item]) {
        img.image = [UIImage imageNamed:@"Modelcheck.png"];
    }else{
        img.image = [UIImage imageNamed:@"Modeluncheck.png"];
    }
    return cell;
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (moneyList.count != 0 || moneyList) {
        return moneyList.count;
    }else{
        return 0;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (![self contenthsHas:arr1 index:indexPath.row]) {
        [arr1 addObject:indexPath];
    }
    if (arr1.count > 1) {
        [arr1 removeObjectAtIndex:0];
    }
    NSLog(@"%li",indexPath.row);
    selectRow = indexPath.row;
    [tableView reloadData];
    //[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
//-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
//    if ([self contenthsHas:arr1 index:indexPath.row]) {
//        [arr1 removeObjectAtIndex:0];
//    }
//    [tableView reloadData];
//}

#pragma mark Custom Methods
-(void)setUI{
    submitBtn.layer.cornerRadius = 5.0;
    arr1 = [NSMutableArray array];
    _tableView.delegate = self;
    _tableView.dataSource = self;
}

-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark GetDomainInfo Delegate 
//获取信息
-(void)didReceiveData{
    if (domainInfoService.InfoDic &&domainInfoService.moneyList) {
        NSLog(@"111");
        domainNameTextField.text = domainInfoService.InfoDic[@"Domain"];
        pastTime.text = domainInfoService.InfoDic[@"Time"];
        moneyTextField.text = domainInfoService.InfoDic[@"ycjifen"];
        moneyList = [domainInfoService.moneyList copy];
        [_tableView reloadData];
        postHud.hidden = YES;
        postHud = nil;
    }
}

//检查数组是否包含item
-(BOOL)contenthsHas:(NSMutableArray *)array index:(NSInteger) row{
    for (NSIndexPath *key  in array) {
        if (key.row == row) {
            return YES;
        }
    }
    return NO;
}

-(void)dealloc{
    domainInfoService = nil;
    postHud = nil;
    submitInfo = nil;
}
- (IBAction)submit:(id)sender {
    if (arr1.count > 0) {
        [self submitInfoRequest];
    }else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请选择年限" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}
-(void)submitInfoRequest{
    if (![Constants isExistenceNetwork]) {
        
    } else {
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在提交，请稍后...";
        }
        
        submitInfo = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        submitInfo.requestMethod = @"POST";
        // 设置超时时间
        submitInfo.timeOutSeconds = 60;
        submitInfo.delegate = self;
        // 设置参数
        action = @"get";
        paramsDict = [NSDictionary dictionary];
        paramsDict = @{@"yumingid":_Id,@"year":moneyList[selectRow][@"year"],@"money":moneyList[selectRow][@"money"],@"uid":UNAME,@"gujishijian":domainInfoService.InfoDic[@"Time"]};//uid会员名
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *str1 = [paramsStr stringByReplacingOccurrencesOfString:@"\\" withString:@""];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,str1];
        
        NSData *paramsData = [result toGBKEncodingData];
        submitInfo.postBody = [paramsData mutableCopy];
        
        [submitInfo startAsynchronous];
    }
}
#pragma mark - ASIHttpRequestDelegate method

- (void)requestFinished:(ASIHTTPRequest *)request {
    NSLog(@"%@",request.responseString);
    postHud.hidden = YES;
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    
    // 1. 是否解析有错误
    if (!err) {
        
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        
        if (errorCode == 0) {
            [SVProgressHUD showSuccessWithStatus:result[@"errorMsg"]];
        }
    } else {
        [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request{
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}

@end
